<template>
  <div class="mobile">
    <a-spin tip="信息提交中，请稍等..." :spinning="submitLoading">
      <a-card class="protectAdd  mobileHeight" :bordered="false">
        <div class="protectAdd-head clearfix">
          <a-alert
            message="严禁发布任何涉密、色情、暴力、侵权等违法违规信息。"
            description="发布的内容通过审核后才可显示。"
            type="warning"
          />
          <a-input placeholder="请输入标题，20字以内" v-model="model.title"/>
          <a-textarea class="protectAdd-head-ms" style="min-height:80px" placeholder="请对好人好事进行描述，至少上传一张图片..."  v-model="model.content" auto-size/>
        </div>
        <div class="protectAdd-describe">
          <div class="uploadImg-box clearfix">
            <div class="uploadImg-list fl" v-for="(v,i) in imgList">
              <img :src="imgList[i].url" @click="previewImage(imgList[i].url)">
              <div class="uploadImg-del"><a @click="delImg(i,imgList[i].fileId)"><i class="iconfont iconshanchu1"></i></a></div>
            </div>
            <div class="uploadImg-list uploadImg fl" @click="chooseImage()">
              <i class="iconfont iconicon-add-3"></i>
            </div>
          </div>
        </div>
        <div class="protectAdd-list clearfix">
          <span class="protectAdd-tips"><i class="iconfont iconxuexiao"></i>学校</span>
          <span class="protectAdd-msg protectAdd-school fr">{{departIds}}</span>
        </div>
        <div class="protectAdd-list clearfix">
          <span class="protectAdd-tips"><i class="iconfont iconshipin"></i>添加视频</span>
          <!--        <span class="protectAdd-msg fr"><i class="iconfont iconyou1"></i></span>-->
          <div style="float:right;">
            <input  ref="videoFiles" type="file" accept="video/*"  capture="camcorder" style="display: none" @change="changeVideoFile($event)">
            <span class="protectAdd-msg protectAdd-ly fr" @touchstart.stop.prevent="avoidMenu" @touchend="createVideo">录制视频</span>
          </div>
          <div style="color:#999999;padding-left: 25px;font-size:14px" >视频上传(视频时长不能超过15s)</div>
          <div v-if="videoFile" class="uplosdVoice-box">
            <div class="uplosdVoice-box-list clearfix">
              <img class="fl" src="../../assets/img/mobile/icon-video.png">
              <span class="fl" id="showFileName">{{ videoName }}</span>
              <a class="fr" @click="delVideo()" style="color: red;"><i class="iconfont iconshanchu1"></i></a>
            </div>
          </div>
        </div>
        <div class="protectAdd-list clearfix" id="content">
          <span class="protectAdd-tips"><i class="iconfont iconyinpin"></i>添加音频</span>
          <span class="protectAdd-msg protectAdd-ly fr" @touchstart.stop.prevent="beginVoice" @touchmove="moveVoice" @touchend="stopVoice">按住录音</span>
          <div class="uplosdVoice-box" v-for="(v,i) in voiceList">
            <div class="uplosdVoice-box-list clearfix" :hidden="openVoiceImg">
              <img :hidden="closeAudioImg" class="fl" @click="openVoice" src="../../assets/img/mobile/icon-audio.png">
              <img :hidden="openAudioImg" class="fl" src="../../assets/img/mobile/icon-audio.gif">
              <span class="fl">{{voiceList[i].fileName}}</span>
              <a class="fr" @click="delVoice()"><i class="iconfont iconshanchu1"></i></a>
            </div>
          </div>
        </div>
        <div :hidden="videoGif" class="protectAdd-ly-img">
          <img src="../../assets/img/mobile/lyicon.gif"></img>
        </div>
        <div class="protectAdd-list clearfix">
          <div>
            <span class="protectAdd-tips"><i class="iconfont icondidian"></i>事发地点</span>
            <span class="protectAdd-msg protectAdd-school fr" @click="changeAddress(location)">{{address}}</span>
            <span class="protectAdd-msg protectAdd-ly fr" @click="changeAddress(location)">微调</span>
          </div>
        </div>
        <a-button class="protectAdd-btn" type="primary" @click="handleChange()" :loading="submitLoading">提交</a-button>
      </a-card>
      <MinorsProtecteAdress ref="locationModal" @ok="handleLocationChange"></MinorsProtecteAdress>
    </a-spin>
    <div class="weui-tabbar">
      <a href="javascript:void(0);" class="weui-tabbar__item" @click="firstPage()">
        <span><i class="iconfont iconzhuye2"></i></span>
        <p class="weui-tabbar__label">首页</p>
      </a>
      <a href="javascript:void(0);" class="weui-tabbar__item" @click="hrhsPage()">
        <span><i class="iconfont icondianzan1"></i></span>
        <p class="weui-tabbar__label">好人好事</p>
      </a>
      <a href="javascript:void(0);" class="weui-tabbar__item" @click="myPage()">
        <span><i class="iconfont iconwode-copy"></i></span>
        <p class="weui-tabbar__label">我的</p>
      </a>
    </div>
  </div>
</template>
<script>
import Template1 from "@views/jeecg/JVxeDemo/layout-demo/Template1";
import { postAction, httpAction, uploadAction } from '@/api/manage'
import wx from 'weixin-js-sdk'
import MinorsProtecteAdress from "@views/mobile/MinorsProtecteAdress";

var baseUrl="";
export default {
  name: 'GoodThingsAdd',
  components: {
    MinorsProtecteAdress,
    Template1,
  },
  data() {
    return {
      beginVoiceTime:0,
      stopVoiceTime:0,
      userId:"",
      realname:"",
      username:"",
      departIds:"",
      classes:"",
      recordTimer:"",
      closeAudioImg:false,
      openAudioImg:true,
      model:{},
      localId : [],
      audioLocalId : [],
      serverId : [],
      imgList:[],
      imgFileArr:[],
      imgFileIdArr:[],
      voiceList:[],
      voiceFileArr:[],
      voiceFileIdArr:[],
      address: "",
      videoGif:true,
      openVoiceImg:true,
      videoName:'',
      videoFile:undefined,
      videoDuration:0,
      lat: '',
      lng: '',
      location:{
        keyword: '',
        location: '',
        center: {
          lat: '',
          lng: ''
        }
      },
      submitLoading:false,
    };
  },
  created(){//加载事件
    document.title = "好人好事";
    this.initBaseUrl();
    this.initData();
    this.getUserDetail();
  },
  methods: {
    handleLocationChange(param) {
      let that = this;
      that.lat = param.lat;
      that.lng = param.lng;
      that.address = param.address;
    },
    initBaseUrl(){
      baseUrl=window._CONFIG['domianURL'];
    },
    initData(){
      let that = this;
      let url=(window.location.href).split('#')[0]
      //获取签名 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115
      postAction("/goodThings/getSignature?url="+encodeURIComponent(url)).then(res=>{
        if(res.success){
          wx.config({
            debug: false,
            appId: res.result.appid, // 必填，公众号的唯一标识
            timestamp:res.result.timestamp , // 必填，生成签名的时间戳
            nonceStr: res.result.nonceStr, // 必填，生成签名的随机串
            signature:res.result.signature,
            jsApiList : [ 'checkJsApi', 'onMenuShareTimeline',
              'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo',
              'onMenuShareQZone', 'hideMenuItems', 'showMenuItems',
              'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem',
              'translateVoice', 'startRecord', 'stopRecord',
              'onVoiceRecordEnd', 'playVoice', 'onVoicePlayEnd',
              'pauseVoice', 'stopVoice', 'uploadVoice', 'downloadVoice',
              'chooseImage', 'previewImage', 'uploadImage', 'downloadImage',
              'getNetworkType', 'openLocation', 'getLocation',
              'hideOptionMenu', 'showOptionMenu', 'closeWindow',
              'scanQRCode', 'chooseWXPay', 'openProductSpecificView',
              'addCard', 'chooseCard', 'openCard' ]
          });
        }
      }).catch(()=>{

      })
      wx.ready(function(){
        wx.getLocation({
          type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
          success: function (res) {
            let latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
            let longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。

            let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
            let x = longitude, y = latitude;
            let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
            let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);

            let lng = (z * Math.cos(theta) + 0.0065);
            let lat = (z * Math.sin(theta) + 0.006);
            let point = new BMap.Point(lng,lat);
            let gc = new BMap.Geocoder()
            gc.getLocation(point, function(rs){
              const addComp = rs.addressComponents
              // 获取省份
              const province = addComp.province
              const city = addComp.city
              const district = addComp.district
              const street = addComp.street
              const streetNumber = addComp.streetNumber
              that.address = province+city+district+street+streetNumber
              that.location.center = {lat: point.lat, lng: point.lng};
              that.lat=point.lat;
              that.lng=point.lng
              that.location.keyword = that.address;
              that.location.location = that.address;


            },{
              poiRadius: 1500,
              numPois :10
            })
          }
        });
      })
    },
    changeAddress(record) {
      this.$refs.locationModal.show(record);
    },
    getUserDetail(){
      let userId = localStorage.getItem("userId")
      postAction("/mobile/getUserById?userId="+userId).then(res=>{
        if(res.success){
          this.userId = res.result.id;
          this.realname = res.result.realname;
          this.username = res.result.username;
          this.departIds = res.result.departIds;
          this.classes = res.result.classes;
        }
      }).catch(()=>{

      })
    },
    chooseImage() {
      let that = this;
      wx.chooseImage({//
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          let localId=res.localIds;//获取到本地localIds
          that.localId=res.localIds;
          that.uploadImg();
        }
      });
    },
    delImg(i,fileId){
      this.imgList.splice(i, 1);
      this.imgFileIdArr.splice(i, 1);
      this.imgFileIdArr.some((item, v) => {
        if (item == fileId ){
          this.imgFileArr.splice(v,1)
          // 在数组的some方法中，如果return true，就会立即终止这个数组的后续循环,所以相比较foreach，如果想要终止循环，那么建议使用some
          return true;
        }
      })
    },
    // 2.2.2 上传图片
    uploadImg() {
      if (this.localId.length == 0) {
        this.$message.warning('请先使用 chooseImage 接口选择图片');
        return;
      }
      var i = 0, length = this.localId.length;
      this.serverId = [];
      this.upload(i,length);
    },
    upload(i,length){
      let that = this;
      wx.uploadImage({
        localId : that.localId[i],
        success : function(res) {
          i++;
          that.serverId.push(res.serverId);
          //将serverId上传至服务器
          postAction("/goodThings/saveWxFiles?mediaId="+res.serverId+"&flag=pic").then(res=>{
            if(res.success){
              that.imgFileArr.push(res.result);
              that.imgFileIdArr.push(res.result.fileId);
              //that.imgFileId = res.result.fileId;
              that.imgList.push({url: baseUrl+'/file/sysFile/download?fileId='+res.result.fileId,fileId:res.result.fileId});
            }
          }).catch(()=>{

          })

          if (i < length) {
            that.upload(i,length);
          }
        },
        fail : function(res) {
          this.$message.warning(JSON.stringify(res));
        }
      });
    },
    beginVoice(){
      this.videoGif = false;
      this.beginVoiceTime = new Date().getTime();
      let that = this;
      clearTimeout(that.recordTimer);//清除定时器
      that.recordTimer = 0;
      that.recordTimer = setTimeout(function () {
        wx.startRecord({
          success: function() {
            localStorage.rainAllowRecord = 'true';
          },
          cancel: function () {
            this.$message.warning('用户拒绝授权录音');
          },
          fail: function(res) {
            this.$message.warning(JSON.stringify(res))
          }
        })
      }, 300);
    },
    moveVoice(){
      clearTimeout(that.recordTimer);//清除定时器
      that.recordTimer = 0;
    },
    stopVoice(){
      this.videoGif = true;
      let that = this
      this.stopVoiceTime = new Date().getTime();
      if ((this.stopVoiceTime - this.beginVoiceTime) < 300) {
        this.beginVoiceTime = 0;
        this.stopVoiceTime = 0;
        this.$message.warning('时间太短了！');
        clearTimeout(that.recordTimer);
      }else{
        wx.stopRecord({ // 微信结束录音接口
          success: res => {
            // 这里将localId保存到data中，用于播放录音和上传到服务端
            that.audioLocalId = res.localId
            that.uploadVoice();
          },
          fail: res => {
            console.log(JSON.stringify(res))
          }
        })
      }
    },
    openVoice(){
      let that = this;
      that.closeAudioImg=true;
      that.openAudioImg=false;
      this.src=""
      wx.playVoice({
        localId: that.audioLocalId // 需要播放的音频的ID，由stopRecord接口获得
      })
      wx.onVoicePlayEnd({
        success: (res) => {
          that.closeAudioImg=false;
          that.openAudioImg=true;
        }
      })
    },
    uploadVoice(){
      let that = this;
      wx.uploadVoice({
        localId: that.audioLocalId, // 需要上传的音频的本地ID，由stopRecord接口获得
        isShowProgressTips: 1, // 默认为1，显示进度提示
        success: async function (res) {
          const serverId = res.serverId // 返回音频的服务器端ID
          //将serverId上传至服务器
          postAction("/goodThings/saveWxFiles?mediaId="+res.serverId+"&flag=voice").then(res=>{
            if(res.success){
              that.voiceFileArr = [];
              that.voiceFileIdArr = [];
              that.voiceList = [];
              that.voiceFileArr.push(res.result);
              that.voiceFileIdArr.push(res.result.fileId);
              that.openVoiceImg = false;
              that.voiceList.push({fileId:res.result.fileId,fileName:res.result.fileName});
            }
          }).catch(()=>{

          })
        },
        fail: function(err) {
          this.$message.warning(err)
        }
      })
    },
    delVoice(i){
      let that = this;
      wx.pauseVoice({
        localId: that.audioLocalId
      });
      this.voiceList.splice(i, 1);
      this.voiceFileIdArr.splice(i, 1);
      this.voiceFileIdArr.some((item, v) => {
          this.voiceFileArr.splice(v,1)
          // 在数组的some方法中，如果return true，就会立即终止这个数组的后续循环,所以相比较foreach，如果想要终止循环，那么建议使用some
          return true;
      })
    },
    handleChange(){
      let userId = this.userId;
      let username = this.username;
      let title = this.model.title;
      let content = this.model.content;
      let address = this.address;
      let lat = this.lat;
      let lng = this.lng;
      if(title == "" || typeof(title) == "undefined"){
        this.$message.warning("请输入标题！");
        return false;
      }else{
        if(title.length > 20){
          this.$message.warning("标题长度过长！");
          return false;
        }
      }
      if(content == "" || typeof(content) == "undefined"){
        this.$message.warning("请对好人好事进行描述！");
        return false;
      }
      content = content.replace(/\n/gm,"<br/>");
      if(this.imgFileIdArr.length == 0){
        this.$message.warning("至少上传一张图片！");
        return false;
      }
      if(this.videoFile && this.videoDuration > 15){
        this.$message.warning("请录制15秒以下的视频！");
        return false;
      }

      let imgFileIdStr = "";
      let voiceFileIdStr = "";
      this.imgFileIdArr.forEach(item =>{
        imgFileIdStr += item+",";
      })
      this.voiceFileIdArr.forEach(item =>{
        voiceFileIdStr += item+",";
      })
      //添加视频附件
      let formData = new FormData();
      if(this.videoFile){
        formData.append('videoFile',this.videoFile)
      }
      this.submitLoading = true;
      uploadAction("/goodThings/add?userId="+userId+"&username="+username+"&title="+title+"&content="+content+"&imgFiles="+imgFileIdStr+"&voiceFiles="+voiceFileIdStr+"&address="+address+"&lat="+lat+"&lng="+lng,formData).then(res=>{
        if(res.success){
          this.$router.push({path:'/MinorsProtecteResult',query:{id:res.result.id,turnFlag:"goodThings"}});
        }else{
          this.$message.warning(res.message);
        }
      }).catch((e)=>{
        this.$message.warning("提交失败!");
      }).finally(()=>{
        this.submitLoading = false;
      })
    },
    previewImage(currentUrl) {
      wx.previewImage({
        current: currentUrl, // 当前显示图片的http链接
        urls: [currentUrl] // 需要预览的图片http链接列表
      })
    },
    //录制视频
    createVideo(){
      this.$refs.videoFiles.dispatchEvent(new MouseEvent('click'))
    },
    //避免菜单出现
    avoidMenu(){},
    //截取文件类型
    getFileType(o){
      var index= o.lastIndexOf(".");
      //获取后缀
      return o.substr(index);
    },
    changeVideoFile(e) {
      let that = this;
      let content = e.target.files[0];
      this.videoFile = content;
      this.videoName = new Date().getTime() + this.getFileType(content.name);
      var url = URL.createObjectURL(content);
      var audioElement = new Audio(url);
      this.videoDuration = 0;
      audioElement.addEventListener("loadedmetadata", function (_event) {
        let duration = audioElement.duration; //时长为秒，小数，182.36
        that.videoDuration = duration;
      })
    },
    //删除视频文件
    delVideo(){
      this.$refs.videoFiles.value = '';
      this.videoFile = undefined;
      this.videoName = "";
      this.videoDuration = 0;
    },
    firstPage(){
      this.$router.push('/MinorsProtecteGuide');
    },
    hrhsPage(){
      this.$router.push('/GoodThingsList');
    },
    myPage(){
      this.$router.push('/PersonalMsg');
    }
  }
}
</script>
